package com.sftz.modules.common.service;

import java.net.URLEncoder;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Encoding;

import com.sftz.framework.constants.CommonConstants;
import com.sftz.framework.rersult.MobileResult;
import com.sftz.framework.service.qiniu.QiniuDownloadService;
import com.uxuexi.core.common.util.Util;

/**
 * @author   朱晓川
 * @Date	 2018年12月11日 	 
 */
@IocBean
public class CommonViewService {

	private static final String[] IMAGE_TYPES = new String[] { "jpg", "png", "jpeg", "gif", "tif", "bmp" };

	@Inject
	private QiniuDownloadService qiniuDownloadService;

	/**
	 * 获取七牛文件访问地址
	 * <p>
	 * 注意:参数文件名必须是不带http://域名部分的纯文件名，比如'a82a2a47-741f-4577-9efc-441c68c3cfe5.pdf'
	 * @param fileName  不带
	 */
	public Map<String, Object> getAuthUrl(final String fileName) {
		if (Util.isEmpty(fileName)) {
			return MobileResult.error("文件原始地址不能为空", null);
		}

		try {
			String fname = URLEncoder.encode(fileName, Encoding.UTF8);
			if (StringUtils.containsAny(fname, IMAGE_TYPES)) {
				//图片直接返回
				fname = CommonConstants.IMAGES_SERVER_ADDR + fname;
				return MobileResult.success("SUCCESS", fname);
			}

			fname = CommonConstants.FILE_SERVER_ADDR + fname;
			fname = qiniuDownloadService.getDownloadUrl(fname);
			return MobileResult.success("SUCCESS", fname);
		} catch (Exception e) {
			e.printStackTrace();
			return MobileResult.error("获取访问地址出错", null);
		}
	}

}
